import os
import psutil

def _kill_processes(pid=None):
    # kill当前进程及子进程
    if pid is not None:
        try:
            parent = psutil.Process(pid)
        except psutil.NoSuchProcess:
            print(f"kill failed, {pid} not exists")
            return False
        try:
            children = parent.children(recursive=True)
            for proc in children + [parent]:
                proc.terminate()
            gone, still_alive = psutil.wait_procs(children + [parent], timeout=5)
            for p in still_alive:
                p.kill()
            print(f"kill {pid} success")
            return True
        except Exception as e:
            print(f"kill {pid} failed: {e}")
            return False
            
pid = None
if (os.path.exists('main.pid')):
    ret = False
    with open('main.pid', 'r') as f:
        pid = int(f.read())
        ret = _kill_processes(pid)
    if (ret == True):
        os.remove('main.pid')


